﻿using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OdooRpcClient.Model.Base;
using PortaCapena.OdooJsonRpcClient;
using PortaCapena.OdooJsonRpcClient.Consts;
using PortaCapena.OdooJsonRpcClient.Models;
using Sunny.UI;
using System;
using System.Collections.Generic;
using WebAssistant.BusinessLogic;
using WebAssistant.BusinessLogic.Model;
using WebAssistant.Common;

namespace Assistant.Tools
{
    public partial class FormJsonEditor : UIForm
	{
        private string HtmlFile = AppDomain.CurrentDomain.BaseDirectory + @"\Html\jsoneditor.html";
        private Reports reports = new Reports();
        private string rName;
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        static OdooConfig config = new OdooConfig(
            apiUrl: "",
            dbName: "",
            userName: "",
            password: ""
            );
        static OdooClient odooClient = new OdooClient(config);

        public FormJsonEditor()
        {
            InitializeComponent();
        }

		public FormJsonEditor(string reportName)
        {
            InitializeComponent();
            InitializeOdoo();

            this.Resize += new System.EventHandler(this.Form_Resize);
            rName = reportName;
            reports = DataAccess.GetReportByReportName(reportName);

            InitializeAsync();
            this.webViewJson.WebMessageReceived += WebView_WebMessageReceived;               
        }

        private void FormJsonEditor_Load(object sender, EventArgs e)
        {
            timer.Interval = 500;
            timer.Tick += new System.EventHandler(this.timerTick);
            timer.Enabled = true;
            if (webViewJson == null && webViewJson.CoreWebView2 == null)
            {
                timer.Start();
            }
            
        }

        private void timerTick(object sender, EventArgs e)
        {
            if (webViewJson != null && webViewJson.CoreWebView2 != null)
            {
                timer.Stop();
                timer.Enabled = true;
                btnDownload_Click(null, EventArgs.Empty);
                //btnDownload.PerformClick();// 也可以模拟鼠标点击button1
            }
        }

        private void InitializeOdoo()
        {
            string[] ConfigKeyList = new string[] {
                "odoo.server.url", "odoo.server.database", "odoo.server.user", "odoo.key", "odoo.server.password"
            };
            foreach (string configkey in ConfigKeyList)
            {
                if (!DataAccess.CheckSettingExists(configkey))
                {
                    ShowWarningDialog("Odoo服务器配置错误！请设置。");
                    return;
                }
            }
            config = new OdooConfig(
                apiUrl: DataAccess.GetSettingByKey("odoo.server.url"),
                dbName: DataAccess.GetSettingByKey("odoo.server.database"),
                userName: DataAccess.GetSettingByKey("odoo.server.user"),
                password: SecurityHelper.DecryptString(DataAccess.GetSettingByKey("odoo.server.password"), DataAccess.GetSettingByKey("odoo.key"))
                );
            odooClient = new OdooClient(config);
        }

        private void Form_Resize(object sender, EventArgs e)
        {
            webViewJson.Size = this.ClientSize - new System.Drawing.Size(webViewJson.Location);
        }


        private async void InitializeAsync()
        {
            await webViewJson.EnsureCoreWebView2Async(null);
            this.webViewJson.Source = new Uri(HtmlFile);
            //btnDownload_Click(null, null);
        }

        private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            reports.DataTemplate = e.TryGetWebMessageAsString();
            var result = DataAccess.UpdateReportDataTemplate(reports);

            if(result > 0)
            {
                ShowSuccessNotifier("更新数据模板成功");
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("action", "set");

            if (reports.DataTemplate != "")
            {
                dict.Add("data", JObject.Parse(reports.DataTemplate));
            }
            else
            {
                dict.Add("data",string.Empty);
            }            
  
            string json = JsonConvert.SerializeObject(dict);
            webViewJson.CoreWebView2.PostWebMessageAsJson(json);
        }

        

        private void btnSave_Click(object sender, EventArgs e)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("action", "get");
            dict.Add("data", "");

            string json = JsonConvert.SerializeObject(dict);
            webViewJson.CoreWebView2.PostWebMessageAsJson(json);
        }

        private async void btnUpload_Click(object sender, EventArgs e)
        {
            var loginResult = await odooClient.LoginAsync();
            if (loginResult.Failed)
            {
                ShowInfoDialog("登陆验证失败，请检查配置是否正确");
            }
            else if (loginResult.Succeed) {
                var reportRepository = new OdooRepository<IrActionsReportOdooModel>(config);
                reportRepository.Config.Context.Language = "zh_CN";
                reportRepository.Config.Context.Timezone = "AsiaChongqing";

                var model = OdooDictionaryModel.Create(() => new IrActionsReportOdooModel()
                {
                    AssistantDataTemplate = DataAccess.GetReportByReportName(rName).DataTemplate
                });
                var result = await reportRepository.UpdateAsync(model, DataAccess.GetReportByReportName(rName).ReportId);

                if (result.Succeed)
                {
                    ShowSuccessNotifier("成功更新到到Odoo");
                }
                else {
                    ShowErrorNotifier("更新到到Odoo识别");
                }
            }
        }

        
    }
}
